package edu.rutgers.moko.data.util;

import java.util.HashMap;
import java.util.List;

import edu.rutgers.moko.data.FieldAccess;
import edu.rutgers.moko.data.ProtectedRule;

public class FieldAccessUtil {
	private HashMap<OMField, FieldAccess> rules = new HashMap<OMField, FieldAccess>();

	public FieldAccessUtil(List<String> rulesAsStrings) {

		for (String ruleString : rulesAsStrings) {
			if (ruleString.trim().length() > 0) {
				FieldAccess fa = new FieldAccess();
				fa.setValuesFromString(ruleString);
				rules.put(fa.getProp(), fa);
			}
		}
	}
	
	public PrivacyMode propertyPrivacyMode(OMField f){
		PrivacyMode res = PrivacyMode.PRIVATE;
		FieldAccess fa = rules.get(f);
		if (fa != null) {
			res = fa.getPrivacyMode();
		}
		return res;
	}
	
	public Integer numberOfRules(OMField f){
		Integer res = 0;
		FieldAccess fa = rules.get(f);
		if (fa != null) {
			res =fa.getProtectedRules().size();
		}
		return res;
	}
	
	public HashMap<Integer, ProtectedRule> propProtectedRules(OMField f) {
		HashMap<Integer, ProtectedRule> res = new HashMap<Integer, ProtectedRule>();
		FieldAccess fa = rules.get(f);
		if (fa != null) {
			Integer i = 0;
			for (ProtectedRule pr : fa.getProtectedRules()) {
				res.put(i++, pr);
			}
		}
		return res;
	}
	
	

	public String privacyModelSelected(OMField tp, PrivacyMode pm) {

		String selected = "";

		if (rules.get(tp) != null && rules.get(tp).getPrivacyMode().equals(pm)) {
			selected = "selected";
		}
		return selected;
	}

	public String actChecked(ProtectedRule pr, ProtectedAccess m) {
		String selected = "";

		if (pr.getType().equals(m)) {
			selected = "checked";
		}
		return selected;
	}

	public String flagChecked(ProtectedRule pr, Flag f) {
		String checked = "";
		
		if (pr!= null && pr.getFlag().equals(f)) {
			checked = "checked";
		}
		
		if(pr == null && Flag.ALLOW.equals(f)){
			checked = "checked";
		}
		return checked;
	}

	public String locValue(ProtectedRule pr) {
		String value = "";
		if (pr.getType().equals(ProtectedAccess.LOCATION)) {
			value = pr.getX1() + ":"
					+ pr.getY1() + ":"
					+ pr.getX2() + ":"
					+ pr.getY2();
		}
		return value;
	}

	public String apValue(ProtectedRule pr) {
		String value = "";

		if (pr.getType().equals(ProtectedAccess.AP)) {
			value = pr.getApId();
		}
		return value;
	}

	public String clValue(ProtectedRule pr) {
		String value = "";

		if (pr.getType().equals(ProtectedAccess.CLIENT)) {
			value = pr.getClientIp()+":"+pr.getSubnetMask();
		}
		return value;
	}
	
	public Boolean isVisible(String ip, OMField field){
		Boolean res = true;
		FieldAccess fa = rules.get(field);
		if(fa!=null){
			res = SecurityUtil.isVisible(ip, fa);
		}
		return res;
	}
	
	public Boolean showMessage(String ip, FieldAccess fa){
		return SecurityUtil.isVisible(ip, fa);
	}

}
